<template>
  <u-popup
    v-model="show"
    mode="bottom"
    border-radius="20"
    :closeable="true"
    :safe-area-inset-bottom="true"
  >
    <view class="df fdc sku-pop bg-white">
      <view class="u-p-30 df fdr">
        <image
          class="pic u-m-r-16"
          :src="choosed_goods.sku_image || detail.main_image"
          mode=""
        ></image>
        <view class="u-p-t-20 u-flex-1 font-24 lh-34">
          <view class="font-36 font-weight-500 u-m-b-24 lh-42"
            >¥<text class="font-50">{{ choosed_goods.price || detail.price }}</text></view
          >
          <view v-if="choosed_goods.stock || detail.stock">
            库存：{{ choosed_goods.stock || detail.stock }}{{ detail.unit || '件' }}</view
          >
          <view v-if="number">已选：{{ number }}{{ detail.unit || '件' }}</view>
        </view>
      </view>
      <scroll-view scroll-y="true" style="height: 482rpx;">
        <view class="sku-main u-p-l-30 u-p-r-30">
          <block v-for="(item, index) in sku_list" :key="index">
            <view class="sku-title">{{ item.name }}</view>
            <view>
              <block v-for="(val, idx) in item.value" :key="val.id">
                <text
                  :class="[
                    'sku-item mb20',
                    { 'sku-item-active': val.active },
                    { 'sku-item-ban': !val.active && val.disabled },
                  ]"
                  @click="handleActive(index, val, idx)"
                  >{{ val.name }}</text
                >
              </block>
            </view>
          </block>
          <!-- 数量 -->
          <view class="sku-num df fdr alc jc-sb">
            <view class="gray2">数量</view>
            <uni-number-box
              @change="changeNumber"
              :value="number"
              :min="detail.min_buy || 1"
              :max="choosed_goods.stock || detail.stock"
            ></uni-number-box>

            <!-- <u-number-box
              @change="changeNumber"
              :positive-integer="true"
              :min="detail.min_buy || 1"
              :max="choosed_goods.stock || detail.stock"
              :value="number"
              :long-press="false"
            >
            </u-number-box> -->
          </view>
        </view>
      </scroll-view>

      <!-- <view class="buy-btn white-color font-32" @click="buyGoods">立即购买</view> -->
      <view class="footer-bar">
        <!-- 限时购 -->
        <view
          class="buy-btn white-color font-32"
          v-if="activity_type === 1 && limit_status == 2"
          @tap="buyGoods(1)"
          >立即购买</view
        >
        <view
          class="buy-btn wait white-color font-32"
          v-else-if="activity_type === 1 && limit_status == 1"
          @tap="buyGoods(1)"
          >¥{{ detail.proce }}原价购买</view
        >
        <!-- 拼团 -->
        <view v-else-if="activity_type === 2" class="flex-row">
          <view class="only-btn main-color u-flex-1 flex-center fdc" @tap="buyGoods(1)">
            <text class="font-24 font-weight-500">¥ {{ detail.price }}</text>
            <text>单独购买</text>
          </view>
          <view class="group-btn white-color u-flex-1 flex-center fdc" @tap="buyGoods(2)">
            <text class="font-24 font-weight-500">¥ {{ activity_info.item_price }}</text>
            <text>{{ activity_info.people_limit }}人开团</text>
          </view>
        </view>
        <view class="buy-btn white-color font-32 font-weight-500" v-else @tap="buyGoods(1)">{{
          btn_text
        }}</view>
      </view>
    </view>
  </u-popup>
</template>

<script>
  import { mapState, mapActions } from 'vuex'
  export default {
    data() {
      return {
        show: false,
        number: 1,
        choosed_id: [], // 选中的sku属性ID
        choosed_goods: {}, // 选中的商品
        // 选择的 sku 组合
        selected_sku: {},
        specification: '', // 已选规格
        base_pic: '',
        goods_info: '', // 商品信息
        sku_info: [],
        sku_list: [],
        btn_text: '立即购买',
      }
    },
    watch: {
      value: {
        handler(val) {
          this.show = val
        },
        immediate: true,
      },
      show: {
        handler(val) {
          if (!val) {
            this.close()
          }
        },
        immediate: true,
      },
    },
    props: {
      value: {
        type: Boolean,
        value: false,
      },
      is_model: {
        type: Boolean,
        value: false,
      },
      detail: Object,
      activity_info: Object,
      add_type: String,
      activity_type: Number, // 1 秒杀 2团购 3满减 4特价热卖 5企业优惠
      limit_status: {
        // 1未开始2 抢购中 3 已结束
        type: Number,
        value: 1,
      },
    },
    onReady() {},
    computed: {
      ...mapState({
        user_info: (state) => state.user_info, // 用户信息
      }),
    },
    methods: {
      ...mapActions(['getUserInfo']),
      reduceNum() {
        if (this.number > 1) {
          this.number = Number(this.number) - 1
        }
      },
      addNum() {
        this.number = Number(this.number) + 1
      },
      changeNumber(val) {
        console.log(val)
        this.number = val
      },
      open() {
        this.$emit('open')
      },
      close() {
        this.$emit('close')
      },
      /**
       * 商品加入购物车
       */
      async addGoodsCart() {
        await this.getUserInfo()
        if (!this.isObjNone(this.user_info)) {
          this.toLogin()
          return
        }
        let params = {
          sku_id: this.choosed_goods.sku_id || this.detail.sku_id,
          num: this.number,
        }
        const res = await this.$api.common.goods('addGoodsCart', params)
        if (res.code === 200) {
          this.close()
          this.showMsg(res.message, 'success')
        }
      },
      // 立即购买
      async buyGoods(is_group) {
        // is_group   1: 不是拼团  2：是拼团
        let size = this.sku_list.length
        let sku_info = this.sku_info
        if (size) {
          if (!this.isAllSelected()) {
            uni.showToast({
              icon: 'none',
              title: '请选择商品规格',
            })
            return
          }
        }
        if (this.btn_text === '加入购物车') {
          this.addGoodsCart()
          return
        }
        let url = ''
        const { activity_type, limit_status } = this
        const { goods_id } = this.detail
        let sku_id = this.choosed_goods.sku_id || this.detail.sku_id
        const {
          group_buy_id,
          group_buy_item_id,
          limit_buy_id,
          limit_buy_item_id,
        } = this.activity_info
        if (is_group === 2) {
          let params = {
            goods_id,
            sku_id,
            number: this.number,
            group_buy_id,
            group_buy_item_id,
          }
          uni.setStorageSync('buy_info', params)
          url = `/views/settlement/settlement?goods_id=${goods_id}`
        } else {
          // 1 秒杀 2团购 3满减 4特价热卖 5企业优惠
          // type 1直接购买 2 购物车购买 3 团购购买
          let params = {
            goods_id,
            sku_id,
            number: this.number,
          }
          console.log('number' + this.number)
          if (activity_type === 1 && limit_status === 2) {
            params.limit_buy_id = limit_buy_id
            params.limit_buy_item_id = limit_buy_item_id
            uni.setStorageSync('buy_info', params)
            params = JSON.stringify(params)
            url = `/views/settlement/settlement?type=1`
          } else if (activity_type === 2) {
            // params.group_buy_id = group_buy_id
            // params.group_buy_item_id = group_buy_item_id
            uni.setStorageSync('buy_info', params)
            params = JSON.stringify(params)
            url = `/views/settlement/settlement?type=1`
          } else {
            uni.setStorageSync('buy_info', params)
            params = JSON.stringify(params)
            url = `/views/settlement/settlement?type=1`
          }
        }
        this.close()
        await this.getUserInfo()
        this.isObjNone(this.user_info) ? this.jump(url) : this.toLogin()
      },
      // 获取sku数据
      loadInfo(sku_info, sku_list, btn_text, is_init) {
        if (!is_init) {
          this.btn_text = btn_text
          return
        }
        this.number = this.detail.min_buy || 1
        this.$forceUpdate()
        sku_list.map((item, index) => {
          item.value.map((val) => {
            item.ks = `s${index + 1}`
            val.id = val.spec_value_id
            val.active = false
            val.disabled = false
          })
        })
        sku_info.map((item) => {
          Object.keys(item.sku_detail).forEach(function (key, index) {
            item[`s${+index + 1}`] = item.sku_detail[key].split(':')[1]
          })
        })
        this.sku_list = sku_list
        this.sku_info = sku_info
        this.btn_text = btn_text
        if (this.sku_list.length) {
          this.initSku()
        } else {
          this.choosed_goods = sku_info[0]
        }
      },
      initSku() {
        // 加载sku后初始化selected_sku
        const { sku_list, selected_sku } = this
        sku_list.map((item, index) => {
          selected_sku[item.ks] = ''
        })
        this.selected_sku = selected_sku
        this.judgeAllItem()
      },
      // 循环判断所有属性是否可选
      judgeAllItem() {
        // 判断库存
        const { sku_list } = this
        sku_list.map((item, index) => {
          item.value.map((val, idx) => {
            if (this.isSkuChooseAble(item.ks, val.id)) {
              // 可点击
              this.$set(val, `disabled`, false)
            } else {
              // 不可点击
              this.$set(val, `disabled`, true)
            }
          })
        })
      },
      isSkuChooseAble(ks, id) {
        const list = this.sku_info
        const selected_sku = this.selected_sku
        // 先假设sku已选中，拼入已选中sku对象中
        let matched_sku = {}
        if (ks && id)
          matched_sku = Object.assign({}, selected_sku, {
            [ks]: id,
          })
        else matched_sku = selected_sku
        // 再判断剩余sku是否全部不可选，若不可选则当前sku不可选中
        let skus_to_check = Object.keys(matched_sku).filter((sku_key) => matched_sku[sku_key] != '')
        let filteredSku = list.filter((sku) =>
          skus_to_check.every((sku_key) => String(matched_sku[sku_key]) == String(sku[sku_key]))
        )

        let stock = filteredSku.reduce((total, sku) => {
          total += Number(sku.stock)
          return total
        }, 0)
        return stock > 0
      },
      // 是否所有规格已选
      isAllSelected() {
        let selected_sku = this.selected_sku
        let list = this.sku_info
        let selected = Object.keys(selected_sku).filter(
          (sku_key_str) => selected_sku[sku_key_str] != ''
        )
        if (this.sku_list.length == selected.length) {
          let filteredSku = []
          let sku_detail_item = {}
          filteredSku = list.filter((sku, index) => {
            Object.keys(selected_sku).forEach((key, idx) => {
              sku_detail_item[
                `spec_id:${this.sku_list[idx].spec_id}`
              ] = `spec_value_id:${this.selected_sku[key]}`
            })
            return JSON.stringify(sku_detail_item) == JSON.stringify(sku.sku_detail)
          })
          this.choosed_goods = filteredSku[0]
          this.specification = filteredSku[0].spec_name
          this.$emit('getSku', this.specification)
        } else {
          this.choosed_goods = ''
          this.specification = ''
          this.$emit('getSku', '')
        }
        return this.sku_list.length == selected.length
      },
      handleActive(key, value, index) {
        let that = this
        let sku_list = that.sku_list
        if (value.disabled) {
          return false
        }
        if (value.active == true) {
          that.$set(sku_list[key].value[index], 'active', false)
          that.selected_sku[sku_list[key].ks] = ''
          that.judgeAllItem()
        } else {
          that.normalClick(key, value, index)
          that.selected_sku[sku_list[key].ks] = value.id
          that.judgeAllItem()
        }
        that.sku_list = sku_list
        that.isAllSelected()
        this.number = this.detail.min_buy || 1
      },
      normalClick(key, value, index) {
        let sku_list = this.sku_list
        for (let i = 0; i < sku_list[key].value.length; i++) {
          if (sku_list[key].value[i].id != value.id) {
            this.$set(sku_list[key].value[i], `active`, false)
          } else {
            this.$set(sku_list[key].value[i], `active`, true)
          }
        }
        this.$forceUpdate()
      },
    },
  }
</script>

<style lang="scss">
  .sku-pop {
    position: relative;
    z-index: 100;
    height: 820rpx;
    border-radius: 20rpx 20rpx 0 0;

    .pic {
      width: 180rpx;
      height: 180rpx;
    }

    .price {
      margin-top: 20rpx;
      color: #ff1c34;
    }

    .sku-main {
      overflow-y: auto;
      flex: 1;
      -webkit-overflow-scrolling: touch;

      &::-webkit-scrollbar {
        width: 0;
        height: 0;
        color: transparent;
      }

      .sku-title {
        width: 100%;
        margin-bottom: 20rpx;
        line-height: 40rpx;
      }

      .sku-item {
        display: inline-block;
        padding: 10rpx 18rpx;
        margin-right: 30rpx;
        margin-bottom: 30rpx;
        font-size: 22rpx;
        line-height: 32rpx;
        background: #f5f5f5;
        border: 2rpx solid #f5f5f5;
        border-radius: 8rpx;

        &:last-child {
          margin-right: 0;
        }
      }

      .sku-item-active {
        color: var(--color);
        border: 2rpx solid var(--color);
      }

      .sku-item-ban {
        color: #999;
      }
    }

    // 数量
    .sku-num {
      width: 100%;
      height: 96rpx;
    }

    // 按钮
    .sku-btn {
      width: 100%;
      height: 98rpx;
      line-height: 98rpx;
      text-align: center;
      background: var(--color);
    }

    // 底部按钮
    .footer-bar {
      width: 100%;
      height: 98rpx;
      background: rgba(255, 255, 255, 1);

      .buy-btn {
        width: 100%;
        height: 98rpx;
        line-height: 98rpx;
        text-align: center;
        background: var(--color);
      }

      .wait {
        background: rgba(55, 186, 56, 1);
      }

      // 拼团
      .only-btn {
        height: 98rpx;
        font-size: 26rpx;
        background: rgba(255, 255, 255, 1);
        border: 2rpx solid var(--color);
        border-radius: 44rpx 0 0 44rpx;
      }

      .group-btn {
        height: 98rpx;
        font-size: 26rpx;
        background: var(--color);
        border-radius: 0 184rpx 184rpx 0;
      }
    }
  }
</style>
